//
//  ModiAppVC.swift
//  HLDesktop
//
//  Created by 黄龙 on 2023/9/4.
//

import UIKit

class ModiAppVC: UIViewController {

    public var changeAppInfoBlock:((_ appData:String)->Void)?
    var currentAppInfo:String = ""
    var newIconPath:String = ""
    var restoreIcoPath:String = ""
    
    lazy var imgLogo: UIImageView = {
        let imgView = UIImageView()
        return imgView
    }()
    
    lazy var edtTitle: UITextField = {
        let field = UITextField()
        field.textAlignment = .right
        field.textColor = .label
        field.font = .systemFont(ofSize: 15)
        field.placeholder = "请输入名称"
        field.delegate = self
        field.returnKeyType = .done
        field.text = ""
        field.clearButtonMode = .whileEditing
        return field
    }()
    
    lazy var edtScheme: UITextField = {
        let field = UITextField()
        field.textColor = .label
        field.font = .systemFont(ofSize: 15)
        field.placeholder = "请输入命令"
        field.delegate = self
        field.returnKeyType = .done
        field.text = ""
        field.clearButtonMode = .whileEditing
        return field
    }()
    
    lazy var mainWorkView: UIView = {
        let workview = UIView()
        return workview
    }()
    
    lazy var colorRowView: UIView = {
        let colorView = UIView()
        return colorView
    }()
    
    let colorPickHeight = 300.0
    lazy var colorCollection: UICollectionView = {
                // FlowLayout自定义设置
        let layout = UICollectionViewFlowLayout.init()
            // 设置item的排列方式 ( horizontal , vertical)
        layout.scrollDirection = .vertical
                // 设置item的size
        let workViewWidth = screen_W - 50
        // 初始化
        let collectview = UICollectionView.init(frame: CGRect(x: 0, y: 0, width: workViewWidth, height: colorPickHeight), collectionViewLayout: layout)
            // 设置背景颜色
        collectview.backgroundColor = .systemBackground.withAlphaComponent(0.65)
        collectview.layer.cornerRadius = 3
        // 设置代理对象
        collectview.delegate = self
        // 设置数据源对象
        collectview.dataSource = self
        collectview.showsVerticalScrollIndicator = true
            // 设置垂直滚动是否滚到item的最底部
        collectview.alwaysBounceVertical = true
            // 设置水平滚动是否滚到item的最右边
//        collectview.alwaysBounceHorizontal = true
            // 开启uicollectionView的分页显示效果
        collectview.isPagingEnabled = false //与scrollview的分页类似,分页滑动，还是平滑
        
        // 注册Cell
        collectview.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "ColorPickCell")

//        // 注册Hearder
//        collectview.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerIdentifier")
//
//        // 注册footer
//        collectview.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footIdentifier")
        
        return collectview
     }()
    
    
    let pickColors: [UIColor] = [#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), #colorLiteral(red: 1, green: 0.5411764706, blue: 0.5019607843, alpha: 1), #colorLiteral(red: 1, green: 0.09019607843, blue: 0.2666666667, alpha: 1), #colorLiteral(red: 0.8352941176, green: 0, blue: 0, alpha: 1),
                                 #colorLiteral(red: 0.7254901961, green: 0.9647058824, blue: 0.7921568627, alpha: 1), #colorLiteral(red: 0, green: 0.9019607843, blue: 0.462745098, alpha: 1), #colorLiteral(red: 0, green: 0.7843137255, blue: 0.3254901961, alpha: 1),
                                 #colorLiteral(red: 0.9176470588, green: 0.5019607843, blue: 0.9882352941, alpha: 1), #colorLiteral(red: 0.8352941176, green: 0, blue: 0.9764705882, alpha: 1), #colorLiteral(red: 0.6666666667, green: 0, blue: 1, alpha: 1),
                                 #colorLiteral(red: 1, green: 1, blue: 0.5529411765, alpha: 1), #colorLiteral(red: 1, green: 0.9176470588, blue: 0, alpha: 1), #colorLiteral(red: 1, green: 0.8392156863, blue: 0, alpha: 1),
                                 #colorLiteral(red: 0.7019607843, green: 0.5333333333, blue: 1, alpha: 1), #colorLiteral(red: 0.3960784314, green: 0.1215686275, blue: 1, alpha: 1), #colorLiteral(red: 0.3843137255, green: 0, blue: 0.9176470588, alpha: 1),
                                 #colorLiteral(red: 1, green: 0.8196078431, blue: 0.5019607843, alpha: 1), #colorLiteral(red: 1, green: 0.568627451, blue: 0, alpha: 1), #colorLiteral(red: 1, green: 0.4274509804, blue: 0, alpha: 1),
                                 #colorLiteral(red: 0.5490196078, green: 0.6196078431, blue: 1, alpha: 1), #colorLiteral(red: 0, green: 0.6901960784, blue: 1, alpha: 1), #colorLiteral(red: 0, green: 0.568627451, blue: 0.9176470588, alpha: 1),
                                 #colorLiteral(red: 1, green: 0.6196078431, blue: 0.5019607843, alpha: 1), #colorLiteral(red: 1, green: 0.2392156863, blue: 0, alpha: 1), #colorLiteral(red: 0.8666666667, green: 0.1725490196, blue: 0, alpha: 1),
                                 #colorLiteral(red: 0.5019607843, green: 0.8470588235, blue: 1, alpha: 1), #colorLiteral(red: 0, green: 0.6901960784, blue: 1, alpha: 1), #colorLiteral(red: 0, green: 0.568627451, blue: 0.9176470588, alpha: 1),
                                 #colorLiteral(red: 0.737254902, green: 0.6666666667, blue: 0.6431372549, alpha: 1), #colorLiteral(red: 0.4745098039, green: 0.3333333333, blue: 0.2823529412, alpha: 1), #colorLiteral(red: 0.3058823529, green: 0.2039215686, blue: 0.1803921569, alpha: 1),
                                 #colorLiteral(red: 0.5176470588, green: 1, blue: 1, alpha: 1), #colorLiteral(red: 0, green: 0.8980392157, blue: 1, alpha: 1), #colorLiteral(red: 0, green: 0.7215686275, blue: 0.831372549, alpha: 1),
                                 #colorLiteral(red: 0.7411764706, green: 0.7411764706, blue: 0.7411764706, alpha: 1), #colorLiteral(red: 0.3803921569, green: 0.3803921569, blue: 0.3803921569, alpha: 1), #colorLiteral(red: 0.1294117647, green: 0.1294117647, blue: 0.1294117647, alpha: 1)
                                 ]
    
    var popMenu:HLPopMenu?
    
    deinit {
        print("没有循环引用才会触发:ModiAppVC.deinit")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = .systemGroupedBackground
        
        self.initView()
        let tapBack = UITapGestureRecognizer(target: self, action: #selector(tapBackView)) //点击任意地方隐藏键盘
        tapBack.cancelsTouchesInView = false
////切记！当手势添加到view上的时候，手势会开始观察view和view上的subviews。当手势被识别的时候，之前的touch将被取消同时不会再传递
        tapBack.delaysTouchesBegan = false
        tapBack.delaysTouchesEnded = false
        view.addGestureRecognizer(tapBack)
//原来是这个手势，会影响collectionView的点击事件的触发,导致item点击无效，要双指同时点击才会触点击效果,
//而设置cancelsTouchesInView=false即可避免冲突,但设置了false之后，点击collectionview的item时，会先触发tapBackView，再触发didselectItem
    }
    
    @objc func tapBackView(){
        self.view.endEditing(true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        self.showPickColor(newIconPath.is_SF_Ico())
        self.colorCollection.reloadData()
    }
    
    func initTopBar(_ topSpace:CGFloat){
        let topView = UIView(frame: CGRect(x: 0, y: 0, width: screen_W, height: topSpace))
        view.addSubview(topView)
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: screen_W, height: 48))
        topView.addSubview(label)
        label.text = "编辑快捷启动项"
        label.font = .boldSystemFont(ofSize: 16)
        label.textColor = .label
        label.textAlignment = .center
        
        let closeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 48, height: 48))
        topView.addSubview(closeButton)
        closeButton.setTitle("取消", for: .normal)
        closeButton.setTitleColor(prjTitleColor, for: .normal)
        closeButton.titleLabel?.font = .boldSystemFont(ofSize: 16)
        closeButton.addActionWithBlock {[weak self] (sender) in
            Vibrations.light.vibrate()
            self?.dismiss(animated: true)
        }
        
        let saveBtn = UIButton(frame: CGRect(x: screen_W-56, y: 0, width: 56, height: 48))
        topView.addSubview(saveBtn)
        saveBtn.setTitle("保存", for: .normal)
        saveBtn.setTitleColor(prjTitleColor, for: .normal)
        saveBtn.titleLabel?.font = .boldSystemFont(ofSize: 16)
        saveBtn.addActionWithBlock { [weak self](sender) in
            Vibrations.light.vibrate()
            self?.saveInfo()
            self?.dismiss(animated: true)
        }
    }

    func initView(){
        self.initTopBar(60)
        
        let workWidth = screen_W - 30
        let workRowHeight = 60.0
        var iTop = 80.0
        var titleWidth = 50.0
//命令组
        let title_2 = UILabel(frame: CGRect(x: 15, y: iTop, width: workWidth, height: 30))
        view.addSubview(title_2)
        title_2.text = "编辑快捷启动命令(非专业人士不推荐修改)"
        title_2.textColor = .secondaryLabel
        title_2.font = .boldSystemFont(ofSize: 14)
        
        iTop += 30
        let work_2 = UIView(frame: CGRect(x: 15, y: iTop, width: workWidth, height: 60))
        view.addSubview(work_2)
        work_2.layer.cornerRadius = 10
        work_2.backgroundColor = .secondarySystemGroupedBackground
        
        let labelCmd = UILabel(frame: CGRect(x: 15, y: 0, width: titleWidth, height: workRowHeight))
        work_2.addSubview(labelCmd)
        labelCmd.text = "命令行"
        labelCmd.textColor = .label
        labelCmd.font = .boldSystemFont(ofSize: 16)
        
        work_2.addSubview(self.edtScheme)
        edtScheme.frame = CGRect(x: 15.0+titleWidth+10.0, y: workRowHeight/2-18, width: workWidth-titleWidth-40.0, height: 36)
        
        
//名称、图标组
        iTop += 60+20
        let title_1 = UILabel(frame: CGRect(x: 15, y: iTop, width: workWidth, height: 30))
        view.addSubview(title_1)
        title_1.text = "编辑快捷启动项名称及图标"
        title_1.textColor = .secondaryLabel
        title_1.font = .boldSystemFont(ofSize: 14)
        
        iTop += 30
        view.addSubview(self.mainWorkView)
        self.mainWorkView.frame = CGRect(x: 15, y: iTop, width: workWidth, height: 2*workRowHeight)
        mainWorkView.layer.cornerRadius = 10
        mainWorkView.backgroundColor = .secondarySystemGroupedBackground
        
        let row_2 = UIView(frame: CGRect(x: 0, y: 0, width: workWidth, height: workRowHeight))
        mainWorkView.addSubview(row_2)
        
        titleWidth = 100.0
        let labelTitle = UILabel(frame: CGRect(x: 15, y: 0, width: titleWidth, height: workRowHeight))
        row_2.addSubview(labelTitle)
        labelTitle.text = "更改快捷名称"
        labelTitle.textColor = .label
        labelTitle.font = .boldSystemFont(ofSize: 16)
        row_2.addSubview(self.edtTitle)
        edtTitle.frame = CGRect(x: 15.0+titleWidth+10.0, y: workRowHeight/2-18, width: workWidth-titleWidth-40.0, height: 36)
        
        let line_2 = CALayer()
        row_2.layer.addSublayer(line_2)
        line_2.frame = CGRect(x: 15, y: workRowHeight-0.5, width: workWidth-15, height: 0.5)
        line_2.backgroundColor = UIColor.tertiarySystemGroupedBackground.cgColor
        
        let row_1 = UIView(frame: CGRect(x: 0, y: workRowHeight, width: workWidth, height: workRowHeight))
        mainWorkView.addSubview(row_1)
        let tapIcoRow = UITapGestureRecognizer(target: self, action: #selector(onTapIcoRow))
        row_1.addGestureRecognizer(tapIcoRow)
        
        let labelIco = UILabel(frame: CGRect(x: 15, y: 0, width: workWidth-15-36-40, height: workRowHeight))
        row_1.addSubview(labelIco)
        labelIco.text = "选择/更改快捷图标"
        labelIco.textColor = .label
        labelIco.font = .boldSystemFont(ofSize: 16)
        
        let btnArrow = UIButton(frame: CGRect(x: workWidth-36, y: workRowHeight/2-18, width: 36, height: 36))
        row_1.addSubview(btnArrow)
        btnArrow.setImage(UIImage(named: "arrowMore@2x.png"), for: .normal)
        btnArrow.addActionWithBlock { [weak self](sender) in //凡是初始化已添加到View上的控件的block，不管会不会触发都得用weakself，否则不会deinit
            self?.showPopmenu()
        }
        
        row_1.addSubview(self.imgLogo)
        imgLogo.frame = CGRect(x: workWidth-36-44, y: 8, width: 44, height: 44)
        imgLogo.layer.cornerRadius = 6
        imgLogo.clipsToBounds = true
        
//颜色选择行
        mainWorkView.addSubview(self.colorRowView)
        self.colorRowView.frame = CGRect(x: 10, y: workRowHeight*2, width: workWidth-20, height: colorPickHeight+1)
        self.colorRowView.isHidden = true
        
        self.colorRowView.addSubview(self.colorCollection)
        
    }
    
    func showPickColor(_ nShow:Bool){
        let iTop = mainWorkView.frame.origin.y
        let workWidth = mainWorkView.frame.width
        let workRowHeight = 60.0
        var maxHeight = 2*workRowHeight+colorPickHeight+10
        if self.view.bounds.height - iTop - maxHeight < 0{ //view.frame = (0,0,screen_w,screen_h-58)
            maxHeight = self.view.bounds.height - iTop - 2*workRowHeight - 34
        }
        if nShow{
            UIView.animate(withDuration: 0.25) {//而此类非添加到View上控件的block，即使用不weakself，也会deinit
                self.mainWorkView.frame = CGRect(x: 15, y: iTop, width: workWidth, height: maxHeight)
                let colorHeight = maxHeight-2*workRowHeight-10
                self.colorRowView.frame = CGRect(x: 10, y: workRowHeight*2, width: workWidth-20, height: colorHeight)
                self.colorCollection.frame = CGRect(x: 0, y: 0, width: workWidth-20, height: colorHeight)
                self.colorRowView.isHidden = false
            }
        }else{
            UIView.animate(withDuration: 0.25) {
                self.mainWorkView.frame = CGRect(x: 15, y: iTop, width: workWidth, height: 2*workRowHeight)
                self.colorRowView.isHidden = true
            }
        }
    }
    
//MARK: - 选择更多图标
    @objc func onTapIcoRow(){//
//        self.newIconPath = "https://a-1251679148.file.myqcloud.com/api/icon/ap3/haierzhijia.png"
//        //test:https://a-1251679148.file.myqcloud.com/api/icon/ap3/jdsmart.png
//        imgLogo.loadImageFrom(imageurl: newIconPath)
        self.tapBackView()
        let iconVC = AppIconVC()
        self.present(iconVC, animated: true)
        iconVC.selectNewIcoBlock = { icoName in
            self.newIconPath = icoName
            self.showPickColor(icoName.is_SF_Ico())
            self.imgLogo.setImageWithStr(imgurl: icoName)
        }
    }
    
    func showPopmenu(){
        //数据源（icon可不填）
        let popData = [(icon:"menu_more@2x.png",title:"更多图标"),
                       (icon:"menu_restore@2x.png",title:"还原图标")]
        
        //设置参数
        let parameters:[HLPopMenuConfigure] = [
            .PopMenuTextColor(.label),
            .popMenuItemHeight(44),
            .PopMenuTextFont(UIFont.systemFont(ofSize: 18))
        ]
        
        let point = imgLogo.convert(imgLogo.frame.origin, to: self.view)
        //init  (test随机生成点位置，注意：arrow点是基于屏幕的位置)
        let cellTop = point.y
        let btnCenterY = cellTop + self.imgLogo.bounds.height/2.0
        
        popMenu = HLPopMenu(menuWidth: 220, arrow: CGPoint(x: point.x, y: btnCenterY),arrowMargin: 12, datas: popData,configures: parameters)
        //show
        popMenu?.showOnTheView(spView: view)
        popMenu?.didSelectMenuBlock = { [weak self](index) in
//而这种非初始化添加的控件，如果没有被执行过，则不用weakself也能deinit，但如果执行过，则就有了强引用，如果没用weakself则会导致不能触发deinit
            if 0 == index{
//选择图标
                self?.onTapIcoRow()
            }else if 1 == index{
//还原
                if let _ = self{
                    self?.newIconPath = self!.restoreIcoPath //对于值来说，虽用了self!也没关系
                    self?.imgLogo.setImageWithStr(imgurl: self!.newIconPath)
                    self?.showPickColor(self!.newIconPath.is_SF_Ico())
                }
            }
        }
    }
    
    
//MARK: - 保存
    func saveInfo(){
        let newScheme = self.edtScheme.text
        if newScheme == nil || newScheme!.isEmpty{
            self.view.showToast("快捷命令不能为空")
            return
        }
        let newTitle = self.edtTitle.text
        if newTitle == nil || newTitle!.isEmpty{
            self.view.showToast("快捷名称不能为空")
            return
        }
        
        let arr = self.currentAppInfo.components(separatedBy: "&|&")
        if arr.count == 3{
            let title = arr[1]
            let scheme = arr[0]
            let icon = arr[2]
            if title != self.edtTitle.text || scheme != self.edtScheme.text || icon != self.newIconPath{
                let result = String(format: "%@&|&%@&|&%@", self.edtScheme.text!,self.edtTitle.text!,self.newIconPath)
                self.changeAppInfoBlock?(result)
            }
        }
    }
    
//MARK: - 编辑block
    func changeAppInfo(_ appInfo:String,completion:@escaping (_ appData:String)->Void){
        changeAppInfoBlock = completion
//通过appInfo更新UI显示
        currentAppInfo = appInfo
        let arr = appInfo.components(separatedBy: "&|&")
        if arr.count == 3{
            self.restoreIcoPath = arr[2]
            self.newIconPath = arr[2]
            imgLogo.setImageWithStr(imgurl: arr[2])
            edtTitle.text = arr[1]
            edtScheme.text = arr[0]
        }
    }
    

}

extension ModiAppVC :UITextFieldDelegate{
    //MARK: - UITextFieldDelegate
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            return true
        }
}

extension ModiAppVC: UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        print("响应点击事件\(indexPath.section)-\(indexPath.row)")
        //原来不在shouldHighlightItemAt处断点，此方法需要2个手指头同时点击这会触发，这是TM什么鬼bug？！
        if pickColors.count>indexPath.row{
            let color = pickColors[indexPath.row]
            let color_hex = color.hexString!
            let path = self.newIconPath
            let tmpArr = path.components(separatedBy: "#syscolor=")
            if 3 == tmpArr.count{
                self.newIconPath = String(format: "%@#syscolor=%@#syscolor=%@", path,color_hex,tmpArr[2])
            }else{//1or2=添加或替前景色即可
                self.newIconPath = String(format: "%@#syscolor=%@", tmpArr[0],color_hex)
            }

            self.imgLogo.setImageWithStr(imgurl: self.newIconPath)
        }

    }

    func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true //不断点就不会触发，这么诡异？！原来是因为对根view做了添加UITapGestureRecognizer的手势导致的冲突。
    }

}


extension ModiAppVC: UICollectionViewDataSource{
        // 设置组数
        func numberOfSections(in collectionView: UICollectionView) -> Int {
            return 1
        }
    
        // 设置每组item个数
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return pickColors.count
        }
    
        // 注册cell
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cellString = "ColorPickCell"
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellString, for: indexPath)
            let tmpColor = pickColors[indexPath.row]
            cell.backgroundColor = tmpColor
            cell.setShadow(shadowColor: prjTitleColor, offset: CGSize(width: 1, height: 1), opacity: 0.25, radius: 21)
            return cell
        }
}

/*
动态设置item的大小、间距等，则需要重写代理
 */
extension ModiAppVC : UICollectionViewDelegateFlowLayout{
    //    MARK: - item Size
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 42, height: 42)
    }
    
//     //     MARK: - 边框距离
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
    
    //    MARK: - 行最小间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }
    
    //    MARK: - 列最小间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }

}
